// File created at: Friday, July 31, 2020
// File encoding  : UTF-8
// Line separator : LF
// Tab stop       : 4 spaces
// IDE            : IntelliJ IDEA community edition
package com.joelzho.vchat.controller;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.joelzho.vchat.service.ChatService;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;

/**
 * @author Joel
 */
@ServerEndpoint("/service/websocket/vchat")
@Component
public class WebsocketServer {

    public static ApplicationContext application;

    private ChatService chatService;

    @OnOpen
    public void onOpen(Session session) {
        chatService = application.getBean(ChatService.class);
    }

    @OnClose
    public void onClose(Session session) throws Exception {
        chatService.logout(session);
    }

    @OnMessage
    public void onMessage(Session session, String message) throws Exception {
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode jsonNode = objectMapper.readTree(message);
        String what = jsonNode.path("what").asText();
        String content = jsonNode.path("content").asText();
        Object ret = null;
        switch (what) {
            case "login":
                ret = chatService.login(session, content);
                break;
            case "logout":
                ret = chatService.logout(session);
                break;
            case "sendMsg":
                ret = chatService.sendChatMessage(session, content);
                break;
            case "onlineUsers":
                ret = chatService.numberOfUsers();
        }
        ObjectMapper out = new ObjectMapper();
        ObjectNode objectNode = out.createObjectNode();
        objectNode.put("what", what);
        objectNode.put("rsp", String.valueOf(ret));
        session.getBasicRemote().sendText(out.writeValueAsString(objectNode));
    }

    @OnError
    public void onError(Session session, Throwable error) throws Exception {
        chatService.logout(session);
    }

}
